package cn.aihongbo.test.shake

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import cn.aihongbo.test.shake.ui.page.ShakeViewModel
import cn.aihongbo.test.shake.ui.theme.TestshakeTheme
import coil.compose.AsyncImage
import java.io.File

class MainActivity : ComponentActivity() {

    private val hShake: HShakeDetector by lazy { HShakeDetector(this@MainActivity) }
    private val viewModel: ShakeViewModel by viewModels()

    var projectionManager: MediaProjectionManager? = null

    val screenCaptureLauncher =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                startService(Intent(this, ScreenCaptureService::class.java).apply {
                    putExtra("resultCode", result.resultCode)
                    putExtra("data", result.data)
                })
            }
        }

    val captureReceive = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val localFile: String? = intent?.getStringExtra("image")
            viewModel.loadImage(localFile)
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            TestshakeTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        viewModel = viewModel, name = "屏幕截图测试：", captureListener = {
                            sendBroadcast(Intent("ACTION_MEDIA_PROJECTION_PERMISSION"))
                        }, cleanListener = {
                            cleanCache()
                        }, modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }

        projectionManager = getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager?
        screenCaptureLauncher.launch(projectionManager?.createScreenCaptureIntent())

        registerReceiver(
            captureReceive, IntentFilter("H_SCREEN_CAPTURE_RESULT"), RECEIVER_EXPORTED
        )

        hShake.listener = {
            viewModel.show()
            //摇一摇截屏
            sendBroadcast(Intent("ACTION_MEDIA_PROJECTION_PERMISSION"))
        }
    }

    override fun onResume() {
        super.onResume()
        hShake.start()
    }

    override fun onPause() {
        super.onPause()
        hShake.stop()
    }

    /**
     * 清理缓存
     */
    fun cleanCache() {
        val fileParent = File(filesDir.absolutePath, H_FILE_CAPTURE_PARENT)
        if (fileParent.isDirectory && fileParent.exists()) {
            val fileList = fileParent.listFiles { file -> file.name.endsWith(".png", true) }
            fileList?.forEachIndexed { index, file ->
                file.delete()
            }
        }
    }
}

@Composable
fun Greeting(
    viewModel: ShakeViewModel,
    name: String,
    captureListener: (() -> Unit) = {},
    cleanListener: (() -> Unit) = {},
    modifier: Modifier = Modifier
) {
    val doRun by viewModel.doRun.collectAsState()
    val showImage by viewModel.showImage.collectAsState()

    Column(modifier = modifier) {
        Column(
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth()
                .background(Color.Yellow)
                .padding(16.dp)
        ) {
            Text(
                text = "$name：$doRun", modifier = modifier
            )
            Row(modifier = Modifier.padding(16.dp)) {
                Button({
                    captureListener.invoke()
                }) {
                    Text("手动截屏")
                }
                Button({
                    cleanListener.invoke()
                }, modifier = Modifier.padding(start = 16.dp)) {
                    Text("清理缓存")
                }
            }
        }
        HorizontalDivider()
        Box(
            modifier = Modifier
                .padding(50.dp)
                .align(Alignment.CenterHorizontally)
                .border(2.dp, Color.Red, RoundedCornerShape(10))
                .padding(18.dp)
        ) {
            AsyncImage(
                model = showImage, contentDescription = ""
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    TestshakeTheme {
        Greeting(ShakeViewModel(), name = "Android")
    }
}